<template>
	<view>
		<!-- 自定义头部导航 -->
		<view class="page">
			<u-text text="发货物料" class="area-header">
			</u-text>
			<view class="body">
				<u--form labelPosition="left" :model="materialData" ref="uForm" class="form" labelWidth="150rpx"
					errorType="toast">
					<view class="upload-scan">
					        <scan-bar id="scanInput" ref="storageUnitScanBarRef" placeholder="扫描包装条码" @code-scanned="getStorageUnitByCode" :key="datekey"></scan-bar>
					    </view>
						<u-form-item label="存货编码" prop="materialCode"  >
						  <u--input v-model="materialData.materialCode" inputAlign="right" clearable
						            border="none" placeholder="存货编码" @clear="handleClear"></u--input>
						</u-form-item>
						<u-form-item label="图号" prop="figureNumber"  >
						  <u--input v-model="materialData.figureNumber" inputAlign="right" clearable
						            border="none" placeholder="图号" @clear="handleClear"></u--input>
						</u-form-item>
					<u-form-item label="物料" prop="materialName" @click="openPickSelect">
						<u--input v-model="materialData.materialName" border="none" disabled disabledColor="#ffffff" inputAlign="right" placeholder="请选择发货物料"></u--input>
						<template #right>
							<u-icon name="arrow-right"></u-icon>
						</template>
					</u-form-item>

				</u--form>
				<u--form labelPosition="left" :model="binData" ref="uForm" class="form" labelWidth="150rpx"
					errorType="toast">
					<u-form-item label="货位号" prop="dstbinCode"  >
					  <u--input v-model="binData.dstbinCode" inputAlign="right" clearable
					            border="none" placeholder="货位号" @clear="handleClearBin"></u--input>
					</u-form-item>
					<u-form-item label="目标货位" prop="dstbinCode" @click="openPickSelectBin">
						<u--input v-model="binData.dstbinCode" border="none" disabled disabledColor="#ffffff" inputAlign="right" placeholder="请选择目标货位"></u--input>
						<template #right>
							<u-icon name="arrow-right"></u-icon>
						</template>
					</u-form-item>
				</u--form>
			</view>
			<view class="area-header">
				<u-text text="包装列表">
				</u-text>
				<u-text :text="'已扫: ' + scanList.length" align="right">
				</u-text>
			</view>
			<view class="upload-scan">
				<scan-bar id="scanInput" ref="scanBarRef" placeholder="扫描包装条码" @code-scanned="getScanResult"
					:key="datekey1"></scan-bar>
			</view>
			<u-line></u-line>
			<view class="list-content">
				<!-- 列表 -->
				<u-list class="list" v-if="sendData && sendData.length > 0" :height="ListViewHeight">
					<u-list-item v-for="(detail, index) in sendData" :key="detail.materialId">
						<view class="card">
							<view class="right">
								<view class="title">
									包装编码:&nbsp;&nbsp;{{detail.extenalCode}}
								</view>
								<view class="body">
									存储区:&nbsp;&nbsp;{{ detail.storageSectionCode }}
								</view>
								<view class="body">
									货位:&nbsp;&nbsp;{{ detail.binCode }}
								</view>
								<view class="body">
									存储批次:&nbsp;&nbsp;{{detail.stockBatch}}
								</view>
							</view>
							<view class="left">
								<u-icon v-if="detail.isChecked == 1" name="checkmark-circle-fill" color="#42b20e" size="30px"></u-icon>
								<u-icon v-if="detail.isChecked == 1" name="close-circle-fill" color="#f56c6c" size="30px" @click="removeDetail(index)"></u-icon>
							</view>
						</view>
						<u-line></u-line>
					</u-list-item>
				</u-list>
				<!-- 空数据 -->
				<u-list v-else :height="ListViewHeight">
					<u-empty mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png"></u-empty>
				</u-list>
			</view>
			<u-line></u-line>
			<view class="search">
				<u-button type="primary" @click="confirmSendData" class="custom-style"
					:loading="posting">确定发货</u-button>
			</view>
			<u-picker :show="showMaterial" :columns="materialList" keyName="materialName" immediateChange @cancel="showMaterial = false" @confirm="materialSelect"></u-picker>
			<u-picker :show="showBin" :columns="binList" keyName="binCode" immediateChange @cancel="showBin = false" @confirm="binSelect"></u-picker>
			<u-modal :show="messageShow" :closeOnClickOverlay="false" title="提示" content="是否要除去此包装"
				:showCancelButton="true" @confirm="messageConfirm" @cancel="messageCancel"></u-modal>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import ScanBar from '@/components/scan-bar/index.vue';
	import { onShow } from '@dcloudio/uni-app';
	import { http } from "../../../utils/http";

	// 重置表单信息 & 光标自动blur
	const scanBarRef = ref();
	const datekey = ref(new Date());
	const datekey1 = ref(new Date());
	const posting = ref(false);
	const ListViewHeight = ref(0);
	const messageShow = ref(false);
	const deleteIndex = ref(0);

	const sendData = ref([]);
	const scanList = ref([]);
	const materialData =reactive({
		materialId: "",
		materialCode: "",
		materialName: "",
		figureNumber: "",
	});
	const binData =reactive({
		dstbinId: "",
		dstbinCode: "",
	});
	/**
	 * 选择成品物料
	 */
	const showMaterial = ref(false);
	const showBin = ref(false);
	const materialList = ref([]);
	const binList = ref([]);
    const storageUnitScanBarRef = ref();
	onShow(async () => {
		ListViewHeight.value = uni.getSystemInfoSync().windowHeight - 250;
		console.log('ListViewHeight.value', ListViewHeight.value);
		materialList.value = [];
		binList.value = [];
		getMaterialList();
		getBin();
	})
	async function getMaterialList() {
		const data = await http({
			url: '/wms/material/queryByList/',
			method: 'POST',
			data: {}
		});
		storageUnitScanBarRef.value.reset();
		let list = data.data;
		list.forEach(item=>{
			item.materialName = `${item.materialCode}-${item.materialName}`
		})
		materialList.value[0] = list;
	}
	// 表单数据定义
	const umodel = reactive({
		materialId: '',
		materialCode: '',
		materialName: '',
		warehouseId: '',
		warehouseCode: '',
		warehouseName: '',
		extenalCode: '',
	});
	async function getStorageUnitByCode(result: any) {
		storageUnitScanBarRef.value.reset();
		datekey.value = new Date()
		if (result) {
			try {
	  umodel.extenalCode = result;
	  const data = await http({
	    url: '/wms/storageunit/getin/' + umodel.extenalCode,
	    method: 'GET',
	    data: {}
	  });
		 materialData.materialId= data.data.materialId,
	     materialData.materialCode =data.data.materialCode,
		 materialData.materialName= data.data.materialName,
	  scanBarRef.value.reset()
	  sendData.value = [];
	  scanList.value = [];
	  const dataone = await http({
	  	url: '/wms/storageunit/getListForFinishProduct/' + materialData.materialId,
	  	method: 'GET',
	  	data: {}
	  }).finally(
	  	scanBarRef.value.reset()
	  );
	  sendData.value = dataone.data;
	  materialData.figureNumber=dataone.data[0].figureNumber;
	  materialData.materialCode=dataone.data[0].materialCode;
	  } catch (error) {
	  	console.error("111");
	  }
	  }
	  else{
		  umodel.extenalCode = '';
	  }
	}
	async function getBin() {
		const data = await http({
			url: '/wms/bin/getByWarehouse/',
			method: 'GET',
			data: {}
		});
		binList.value[0] = data.data;
		storageUnitScanBarRef.value.reset();
	}
	async function materialSelect(e) {
		if (e.value.length) {
			materialData.materialId = e.value[0].id;
			materialData.materialName = e.value[0].materialName;
			sendData.value = [];
			scanList.value = [];
			const data = await http({
				url: '/wms/storageunit/getListForFinishProduct/' + materialData.materialId,
				method: 'GET',
				data: {}
			}).finally(
				scanBarRef.value.reset()
			);
			sendData.value = data.data;
			materialData.figureNumber=data.data[0].figureNumber;
			materialData.materialCode=data.data[0].materialCode;
		} else {
			materialData.materialId = '';
			sendData.value = [];
		}
		console.log(materialData.materialName);
		showMaterial.value = false;
	}
	function binSelect(e) {
		if (e.value.length) {
			binData.dstbinId = e.value[0].id;
			binData.dstbinCode = e.value[0].binCode;
		}
		showBin.value = false;
	}
	function openPickSelect() {
		showMaterial.value = true;
		uni.hideKeyboard();
		complete(materialData.materialCode);
	}
	function openPickSelectBin() {
		showBin.value = true;
		uni.hideKeyboard();
		completeBin(binData.dstbinCode);
	}
	function complete(materialCode) {
	  materialList.value[0] = materialList.value[0].filter(item => {
	    // 使用正则表达式进行模糊匹配
	    let regex = new RegExp(materialCode, "i"); // "i" 表示忽略大小写
	    return regex.test(item.materialCode);
	  });
	}
	function completeBin(binCode) {
	  binList.value[0] = binList.value[0].filter(item => {
	    // 使用正则表达式进行模糊匹配
	    let regex = new RegExp(binCode, "i"); // "i" 表示忽略大小写
	    return regex.test(item.binCode);
	  });
	}
	function handleClear()
	{
		getMaterialList();
	}
	function handleClearBin()
	{
		getBin();
	}
	// 获取扫码结果
	async function getScanResult(result) {
		scanBarRef.value.reset()
		datekey1.value = new Date()
		console.log('扫码结果', result);
		const index = sendData.value.findIndex(item => item.extenalCode === result);
		
		if (index == -1) {
			uni.$u.toast('请扫描正确的包装条码！');
			scanBarRef.value.reset();
		} else {
			const scannedStorageUnit = scanList.value.find(item => item.extenalCode === result);
			if (scannedStorageUnit) {
				uni.$u.toast('这个包装已经被扫描过！');
				scanBarRef.value.reset();
			} else {
				 // 标记条码为已检查
				            sendData.value[index].isChecked = 1;
				            // 更新 dstbinId 和 dstbinCode
				            const updatedItem = { ...sendData.value[index], dstbinId: binData.dstbinId, dstbinCode: binData.dstbinCode };
				            // 将更新后的条码信息添加到 scanList
				            scanList.value.unshift(updatedItem);
				            console.log(scanList.value);
				            scanBarRef.value.reset();
			}
		}
	}

	async function confirmSendData() {
		if (scanList.value.length == 0) {
			uni.$u.toast('请扫描需要出库的包装条码！');
			return;
		}
		console.log("111",scanList.value);
		console.log(binData);
		scanList.value[0].dstbinCode=binData.dstbinCode;
		scanList.value[0].dstbinId=binData.dstbinId;
		const data = await http({
			url: '/wms/finishedProduct/send/',
			method: 'POST',
			data: scanList.value
		});

		if (data.data.code == 200) {
			uni.$u.toast('发货成功！');
			reset();
		}
	}
	
	async function messageConfirm() {
		messageShow.value = false;
		const extenalCode = sendData.value[deleteIndex.value].extenalCode;
		const index = scanList.value.findIndex(item => item.extenalCode === extenalCode);
		sendData.value[deleteIndex.value].isChecked = 0;
		scanList.value.splice(index, 1);
		scanBarRef.value.reset();
	}
	
	function messageCancel() {
		messageShow.value = false;
		scanBarRef.value.reset();
	}
	
	function removeDetail(index : any) {
		deleteIndex.value = index;
		messageShow.value = true;
	}
	
	function reset() {
		materialData.materialName = "";
		materialData.materialCode = "";
		materialData.materialId = "";
		materialData.figureNumber = "";
		sendData.value = [];
		scanList.value = [];
		binData.dstbinId= "";
		binData.dstbinCode= "";
	}
</script>

<style lang="scss" scoped>

	.page {
		display: flex;
		flex-direction: column;
	}
	
	.body {
		padding: $uni-page-padding;
	}

	.upload-scan {
		padding: 10px 40rpx 10px 40rpx;
	}

	.area-header {
		color: #909193;
		padding: 10px 15px;
		margin-bottom: 0;
		font-size: 15px;
		background-color: #f3f4f6;
		display: flex;
	}

	.list-content {
		padding: $uni-page-padding;
	
		.list-title {
			line-height: 40px;
			font-size: 14px;
			color: rgba(0, 0, 0, 0.4);
		}
	
		.list {
			.card {
				margin-top: 5px;
				margin-bottom: 10px;
				border-radius: 7px;
				display: flex;
				align-items: center;
				padding: 10px 0;
				transition: all 300ms ease;
				box-shadow: 0 0 1px rgba(0, 0, 0, 0.1);
	
				.left {
					flex-basis: 120rpx;
					padding-right: 10px;
					text-align: right;
					font-size: 13px;
					display: flex;
					justify-content: space-between;
	
					.enter {
						line-height: 20px;
						margin-bottom: 5px;
					}
	
					.number {
						font-size: 13px;
						line-height: 18px;
					}
	
					// :deep(.u-icon--right) {
					// 	flex-direction: row-reverse;
					// }
				}
	
				.right {
					flex: 1;
	
					.title {
						font-size: 15px;
						line-height: 20px;
						margin-bottom: 5px;
						font-weight: 700;
					}
	
					.body {
						padding-left: 0;
						font-size: 13px;
						line-height: 18px;
					}
				}
			}
		}
	}

	.search {
		display: flex;
		flex: 1;

		.custom-style {
			// width: 120px;
			margin: 12px 5px 5px;
			height: 40px;
			border-radius: 8px;

			&:nth-child(1) {
				flex: 1
			}

			&:nth-child(2) {
				flex: 3
			}
		}
	}
</style>